package org.mili.ticketeer.dao;

import org.mili.ticketeer.dao.query.v2.QueryBuilder;
import org.mili.ticketeer.dto.Identifieable;
import org.mili.ticketeer.dto.Priority;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PriorityDao extends AbstractDao {

    private Map<String, Priority> cache = new HashMap<>();
    private Map<Integer, Priority> idCache = new HashMap<>();

    public PriorityDao() {
        super(Priority.Fields.values(), Priority.Fields.values(), Priority.TABLE);
    }

    public ModificationResult write(final Priority priority) throws DaoException {
        cache.clear();
        idCache.clear();
        return createOrUpdate(priority);
    }

    public Priority findByName(final String name) throws DaoException {
        Priority priority = cache.get(name.toLowerCase());
        if (priority == null) {
            priority = (Priority) readSingle(
                    new PriorityRowTransformer(),
                    QueryBuilder.createQueryBuilder()
                            .select()
                            .fields(Identifieable.Fields.ID, fields)
                            .from(table)
                            .where()
                            .eq(Priority.Fields.NAME, name)
                            .build());
            cache.put(name.toLowerCase(), priority);
        }
        return priority;
    }

    public Priority findById(final int id) throws DaoException {
        Priority priority = idCache.get(id);
        if (priority == null) {
            priority = (Priority) readSingle(new PriorityRowTransformer(),
                    QueryBuilder.createQueryBuilder()
                            .select()
                            .fields(Identifieable.Fields.ID, fields)
                            .from(table)
                            .where()
                            .eq(Identifieable.Fields.ID, id)
                            .build());

            idCache.put(id, priority);
        }
        return priority;
    }

    public List<Priority> getPriorities() throws DaoException {
        return read(new PriorityRowTransformer());
    }

    class PriorityRowTransformer implements RowTransformer<Priority> {
        @Override
        public Priority transform(ResultSet resultSet) throws SQLException {
            Priority priority = new Priority();
            priority.setId(resultSet.getInt(Identifieable.Fields.ID.name()));
            priority.setName(resultSet.getString(Priority.Fields.NAME.name()));
            priority.setPriority(resultSet.getInt(Priority.Fields.PRIORITY.name()));
            return priority;
        }
    }


}
